/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.bot.server;

import com.sun.net.httpserver.HttpExchange;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.regex.Pattern;

/**
 *
 * @author phichidev
 */
public class RequestWorker implements Runnable {

    private RequestHandlerRegistry httpRequestRegistry;
    private ArrayBlockingQueue<HttpExchange> httpExchanges;
    private RequestHandler defaultRequestHandler;

    public RequestWorker(RequestHandlerRegistry httpRequestRegistry, ArrayBlockingQueue<HttpExchange> httpExchanges) {
        this.httpRequestRegistry = httpRequestRegistry;
        this.httpExchanges = httpExchanges;
    }

    public void setDefaultRequestHandler(RequestHandler defaultRequestHandler) {
        this.defaultRequestHandler = defaultRequestHandler;
    }

    @Override
    public void run() {
        while (true) {
            try {
                HttpExchange httpExchange = httpExchanges.take();
                String url = httpExchange.getRequestURI().toString();
                boolean flag = false;
                for (Entry<String, RequestHandler> entry : httpRequestRegistry.entrySet()) {
                    Pattern pattern = Pattern.compile(entry.getKey());
                    if (pattern.matcher(url).matches()) {
                        RequestHandler httpRequestListener = entry.getValue();
                        httpRequestListener.handleRequest(httpExchange);
                        flag = true;
                        break;
                    }
                }
                if (!flag && defaultRequestHandler != null) {
                    defaultRequestHandler.handleRequest(httpExchange);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
